# -*- coding: utf-8 -*-

import requests
import json
import hashlib
import base64

"""

接口测试代买
Created on Tue Jul 27 12:41:39 2021

@author: Administrator
"""

def getHtml(url, paramss, type = "post"):
    try:
        file = open("tokenwx.txt", "r")
        fileData = file.read()
        token =""
        try:
            json_to_python = json.loads(fileData)
            token = json_to_python['data']["token"]
            
            # 本地获取了登录数据就需要接口鉴权
            # ?act=18782927715_b3e446d18285d30e937d654bf3740418_9c5bd25aab33230875d97df1e335c053&cdt=1627367945599&uid=40026
            # act= 手机号+密码+md5（手机号+密码+时间戳） cdt 时间戳 
            
        except Exception:
            print("===json 解析出错")
        file.close()
        header = {'Content-Type':'application/json; charset=UTF-8',
            "app_type":"1",
                  "version":"1.21.38-test210617-1",
                  "token": token}  
        # params:{uid=40076, oid=43296, key=43296, type=0, gid=43, gift_type=1, num=1, plat=android, yzt=56070fae6b37ad772ae6ed994a082038}
        # 代理
        # prox = {}
        
        if "post" == type:
            data = requests.post(url,data = paramss, headers=header,timeout=2)
        else:
            data = requests.get(url,data = paramss, headers=header,timeout=2)
        data.encoding = "utf-8"
        # print(data.text)
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# 有的接口需要yzt参数
def getYzt(mydata):
    mydata = str(mydata) + "c2hvdWh1bGlmZWF3ZWxpYW8="
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    

# 登录之后获取用户id
def getUid():
    file = open("tokenwx.txt", "r")
    fileData = file.read()
    try:
        json_to_python = json.loads(fileData)
        file.close()
        return json_to_python['data']["uid"]
    except Exception:
        file.close()
        return ""


"""
==============================================================================
    实际用户API接口调用
==============================================================================
"""
    
URLHOST = "http://localhost" # http://139.155.88.162  "http://shouhulife.vicp.cc/" # "http://localhost:8080" #
# 登录将登录数据放在文件中
def login(phone, code):
    # phone = "18782927715"
    # paramss =  '{"uid":"40026", "amount":"9800"}'
    paramss = {"code":"202088", "phone":phone, "did":"imei866182040064619", "code": code,
               "mac":"3C:86:D1:5A:EB:13", "ip":"192.168.0.201", "brand":"vivo_V1928A", "sys_version":"28_9",
               "sys":"androidphone", "app_version":"1.21.39-test210726_18",
               "mart":"and-0", "lat":"30.554378",
               "lng":"104.07132", "city_code":"510100", "city":"成都市",
               "province_code":"510000", "province":"四川省","spreaduid":"0", "yzt":getYzt(phone)}
    
    # dd = str(paramss)
    dd = json.dumps(paramss)
    # print(dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = getHtml(URLHOST+"/login", par)
    print(data)
    file = open("tokenwx.txt", "w+")
    file.write(data)
    file.close()

# 发送验证码
def sendCode(phone):
    paramss = {"phone": phone}
    data = getHtml(URLHOST+"/public/user/sendphonecode", json.dumps(paramss))
    return data

# 测试多账户登录
def testUserLogin(index):
    userList = ["18782927715","13540124221","17190085924","13540124222","13540124223",
                "13540124224","13540124225","13540124226","13540124227","13540124228","13540124229"]
    # for i in range(7,len(userList)):
    #     login(userList[i])
    #     getacc()
    try:
        data = sendCode(userList[index])
        print(data)
        json_to_python = json.loads(data)
        login(userList[index], json_to_python["data"])
    except Exception:
        print("==json error")

# 签到
def sign():
    paramss = {"uid": getUid(),  "sysVersion":"28_9",
               "sys":"androidphone", "appVersion":"1.21.39-test210726_18",
               "mart":"and-0", "lat": "30.554378",
               "lng": "104.07132", "cityCode": "510100", "city": "成都市",
               "provinceCode": "510000", "province": "四川省"}
    data = getHtml(URLHOST + "/user/signapp", json.dumps(paramss))
    print(data)

# 用户修改资料
def updataUserInfo():
    paramss = {"uid": getUid(),"yzt":getYzt(getUid()), "sex":"男"}
    data = getHtml(URLHOST+"/user/updatauserinfo", json.dumps(paramss))
    print(data)


# 用户添加相册图片
def addPhoto():
    paramss = {"uid": getUid(), "photoname": "a6e79820-2758-4270-b545-fcdfaf950c40.jpg"}
    data = getHtml(URLHOST + "/user/addphoto", json.dumps(paramss))
    print(data)

# 上传用户头像
# 这里写的是image/jpeg，也可以是png/jpg
def updataHead(img_path, img_type='image/jpeg'):
    file = open("tokenwx.txt", "r")
    fileData = file.read()
    token = ""
    try:
        json_to_python = json.loads(fileData)
        token = json_to_python['data']["token"]

        # 本地获取了登录数据就需要接口鉴权
        # ?act=18782927715_b3e446d18285d30e937d654bf3740418_9c5bd25aab33230875d97df1e335c053&cdt=1627367945599&uid=40026
        # act= 手机号+密码+md5（手机号+密码+时间戳） cdt 时间戳

    except Exception:
        print("===json 解析出错")
    file.close()
    header = {"app_type": "1",
              "version": "1.21.38-test210617-1",
              "token": token}

    img = open(img_path, 'rb')
    # 注意这里一定要设置图片类型
    file = {'file': (img_path, img, img_type)}
    paramss = {'type': 'photo'}
    print("上传图片")
    response = requests.post(url=URLHOST+"/upload",data = paramss, files=file, headers=header)

    print(response.text)


# 用户删除相册图片
def delPhoto(id):
    paramss = {"uid": getUid(), "id": id}
    data = getHtml(URLHOST + "/user/delphoto", json.dumps(paramss))
    print(data)

# 用户设为封面
def facePhoto():
    paramss = {"uid": getUid(), "id": "1"}
    data = getHtml(URLHOST + "/user/facephoto", json.dumps(paramss))
    print(data)

# 用户照片审核
def verifyPhoto(verify):
    paramss = {"uid": getUid(), "id": "1", "verify": verify}
    data = getHtml(URLHOST + "/user/verifyphoto", json.dumps(paramss))
    print(data)


# 获取未审核照片列表
def getVerifyList():
    paramss = {"uid": getUid(), "page": "1", "size": "5"}
    data = getHtml(URLHOST + "/user/verifyphotolist", json.dumps(paramss), "get")
    print(data)

# 获取自己的照片列表
def getmyPhotoList():
    paramss = {"uid": getUid(), "page": "1", "size": "5"}
    data = getHtml(URLHOST + "/user/photolist", json.dumps(paramss), "get")
    print(data)

# 获取别人的照片列表
def getUserPhotoList(oid):
    paramss = {"uid": getUid(),"oid": oid, "page": "1", "size": "5"}
    data = getHtml(URLHOST + "/user/userphotolist", json.dumps(paramss), "get")
    print(data)

# 关注用户
def addFollow(oid):
    paramss = {"uid": getUid(),"oid": oid}
    data = getHtml(URLHOST + "/follow/add", json.dumps(paramss))
    print(data)

# 取消关注
def delFollow(id):
    paramss = {"uid": getUid(), "oid": id}
    data = getHtml(URLHOST + "/follow/del", json.dumps(paramss))
    print(data)

# 获取我关注的人列表
def getUserFollowList():
    paramss = {"uid": getUid(), "page": "2", "size": "2"}
    data = getHtml(URLHOST + "/follow/mylist", json.dumps(paramss), "get")
    print(data)

# 获取我关注的人列表
def getUser1FollowList():
    paramss = {"uid": getUid(), "page": "1", "size": "2"}
    data = getHtml(URLHOST + "/follow/userlist", json.dumps(paramss), "get")
    print(data)

# 发布动态
def dynamic():
    paramss = {"uid": getUid(), "content": str(base64.b64encode("动态内容".encode('utf-8')), 'utf-8'),
               "videoPath": "",
               "imgPath": "images/photo/c5828111-40db-46ad-9a39-742d8fa40a73.jpg", "lat": "30.554378",
               "lng": "104.07132", "cityCode": "510100", "city": "成都市",
               "provinceCode": "510000", "province": "四川省"}
    data = getHtml(URLHOST + "/dynamic/add", json.dumps(paramss))
    print(data)

# 删除动态
def dynamicDel(id):
    paramss = {"uid": getUid(), "id": id}
    data = getHtml(URLHOST + "/dynamic/del", json.dumps(paramss))
    print(data)

# 查询我的动态列表
def myDynamicList():
    paramss = {"uid": getUid(), "page": 1, "size":2, "oid": 14}
    data = getHtml(URLHOST + "/dynamic/mydynamiclist", json.dumps(paramss),"get")
    print(data)
# 查询指定用户的动态列表
def userDynamicList(oid):
    paramss = {"uid": getUid(), "page": 1, "size":2, "oid": oid}
    data = getHtml(URLHOST + "/dynamic/userdynamiclist", json.dumps(paramss),"get")
    print(data)
# 查询所有用户的动态列表
def allDynamicList():
    paramss = {"uid": getUid(), "page": 1, "size": 10}
    data = getHtml(URLHOST + "/dynamic/alldynamiclist", paramss,"get")
    print(data)

# 动态点赞
def starDynamic(id):
    paramss = {"uid": getUid(), "messageid": id}
    data = getHtml(URLHOST + "/dynamic/star", json.dumps(paramss) )
    print(data)

# 动态评论
def replyDynamic(id):
    paramss = {"uid": getUid(), "messageid": id, "replyContent": str(base64.b64encode("动态回复内容111".encode('utf-8')), 'utf-8'), "parentId":10}
    data = getHtml(URLHOST + "/dynamic/reply", json.dumps(paramss) )
    print(data)
# 查询动态评论列表
def myDynamicReplyList():
    paramss = {"uid": getUid(), "page": 1, "size":2,"messageid":7,"parentId":0}
    data = getHtml(URLHOST + "/dynamic/getreplylist", paramss,"get")
    print(data)


# 主模块
# ======================================================================================================================
if __name__ == '__main__':
    # ======================
    # 用户登录
    # testUserLogin(1)
    # 签到
    # sign()
# 动态评论列表
    myDynamicReplyList()
    # 动态品论
    # replyDynamic(7)
    # 动态点赞
    # starDynamic(2)
    # 我的动态列表
    # myDynamicList()
    # userDynamicList(14)
    # allDynamicList()
    # 发布动态
    # dynamic()
    # 删除动态
    # dynamicDel(1)

    # 获取关注我的人
    # getUser1FollowList()
    # 获取我关注的人列表
    # getUserFollowList()

    # 关注用户
    # addFollow(20)
    # 取消关注
    # delFollow(20)

    # 更新用户资料
    # updataUserInfo()
    # 用户照片审核 1 通过 2 不通过
    # verifyPhoto(2)

    # updataHead("D:\\myFile\\aa.jpg")
    # 用户添加相册图片
    # addPhoto()
    # 用户删除相册图片
    # delPhoto(1)
    # 用户设为封面
    # facePhoto()
    # 获取未审核照片列表
    # getVerifyList()
    # 获取自己的照片列表
    # getmyPhotoList()
    # 获取别人的照片列表
    # getUserPhotoList(16)

